package servlets;

import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.PersonneDAO;

import modele.Personne;

/**
 * Servlet implementation class CreerCompte
 */
public class CreerCompte extends HttpServlet {
	private static final String URL_FORMULAIRE = "/WEB-INF/creerCompte.jsp";
	private static final String URL_FIN_INSCRIPTION = "/WEB-INF/finInscription.jsp";

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher vue;
		if (request.getSession(true).getAttribute("user") == null) {
			vue = getServletContext().getRequestDispatcher(URL_FORMULAIRE);
		} else {
			vue = getServletContext().getRequestDispatcher(URL_FIN_INSCRIPTION);
		}
		vue.forward(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		boolean ok = true;
		RequestDispatcher vue;

		String nom = request.getParameter("nom");
		if (nom == null || nom.matches("^ *$")) {
			request.setAttribute("msgNom", "Nom obligatoire");
			ok = false;
		}

		String prenom = request.getParameter("prenom");
		if (prenom == null || prenom.matches("^ *$")) {
			request.setAttribute("msgPrenom", "Prénom obligatoire");
			ok = false;
		}

		String sDateNaissance = request.getParameter("dateNaissance");
		SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		if (sDateNaissance == null || sDateNaissance.matches("^ *$")) {
			request.setAttribute("msgDateNaissance",
					"Date de naissance obligatoire");
			ok = false;
		}	

		Date dateNaissance = null;
		try {
			java.util.Date date = df.parse(sDateNaissance);
			dateNaissance = new java.sql.Date(date.getTime());
			System.out.println(df.format(dateNaissance));

			if (!sDateNaissance.equals(df.format(dateNaissance))) {
				request.setAttribute("msgDateNaissance",
					"La date doit avoir des jour, mois et année valides");
			}
		} catch (ParseException e) {
			request.setAttribute("msgDateNaissance",
					"La date doit être au format jj/mm/aaaa");
		}

		String telephone = request.getParameter("numeroTelephone");
		if (telephone == null || telephone.matches("^ *$")) {
			request.setAttribute("msgTelephone",
					"Numero de téléphone obligatoire");
			ok = false;
		} else if (telephone.length() != 10) {
			request.setAttribute("msgTelephone",
					"Le numéro de téléphone doit contenir 10 chiffres");
			ok = false;
		} else if (!telephone.matches("^[0-9,;]+$")) {
			request.setAttribute("msgTelephone",
					"Le numéro de téléphone ne peut contenir que des chiffres");
			ok = false;
		}


		String adresse = request.getParameter("adresse");
		if (adresse == null || adresse.matches("^ *$")) {
			request.setAttribute("msgAdresse", "Adresse obligatoire");
			ok = false;
		}

		String ville = request.getParameter("ville");
		if (ville == null || ville.matches("^ *$")) {
			request.setAttribute("msgVille", "Ville obligatoire");
			ok = false;
		}

		String codePostal = request.getParameter("codePostal");
		if (codePostal == null || codePostal.matches("^ *$")) {
			request.setAttribute("msgCodePostal", "Code postal obligatoire");
			ok = false;
		} else if (codePostal.length() != 5 ){
			request.setAttribute("msgCodePostal", "Code postal doit contenir 5 chiffres");
			ok = false;
		} else if (!codePostal.matches("^[0-9,;]+$")) {
			request.setAttribute("msgCodePostal",
					"Le code postal ne peut contenir que des chiffres");
			ok = false;
		}

		String email = request.getParameter("email");
		if (email == null || email.matches("^ *$")) {
			request.setAttribute("msgEmail", "Email obligatoire");
			ok = false;
		} else if (!email.matches("\\w([-\\.]?\\w+)*@\\w([-\\.]?\\w+)*\\.\\w+")) {
			request.setAttribute("msgEmail",
					"Le format de l'email est incorrect");
			ok = false;
		}

		String password = request.getParameter("password");
		if (password == null || password.matches("^ *$")) {
			request.setAttribute("msgPassword", "Mot de passe obligatoire");
			ok = false;
		} else if (password.length() < 6) {
			request.setAttribute("msgPassword",
					"Mot de passe doit contenir 6 caractères minimum");
			ok = false;
		}

		String password2 = request.getParameter("password2");
		if (password2 == null || password2.matches("^ *$")) {
			request.setAttribute("msgPassword2", "Mot de passe obligatoire");
			ok = false;
		} else if (password2.length() < 6) {
			request.setAttribute("msgPassword2",
					"Mot de passe doit contenir 6 caractères minimum");
			ok = false;
		}

		if (!password.equals(password2)) {
			request.setAttribute("msgPassword2",
					"Les mots de passe sont différents");
			ok = false;
		}

		String errorException = "";
		if (ok) {
			System.out.println("Inscription réussie");			
			Personne user = new Personne(-1, nom, prenom, dateNaissance,
					telephone, adresse, codePostal, ville, email, password);
			PersonneDAO dao = null;
			try {
				dao = new PersonneDAO();			
				dao.inserer(user);
				request.getSession(true).setAttribute("user", user);
				response.sendRedirect("CreerCompte");
			} catch (SQLException exc) {
				errorException = exc.getMessage();
				request.setAttribute("msgForm", exc.getMessage());
				ok = false;
			}
		}

		if (!ok) {

			System.out.println("Inscription non réussie");
			System.out.println(errorException);
			vue = getServletContext().getRequestDispatcher(URL_FORMULAIRE);
			vue.forward(request, response);
		}
	}
}
